# -*- coding: utf-8 -*-

import datetime,urllib, cgi, os
import logging

from google.appengine.api import memcache, urlfetch
from google.appengine.api.labs import taskqueue
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from xml.dom import minidom

from gaesessions import get_current_session

webapp.template.register_template_library('filter')

class log(webapp.RequestHandler):
  def post(self):
	"""Page de login, récupération de la date de connexion, de l'avatar."""
	session = get_current_session()
	key = self.request.get('key')
	skey = s.key()
	pseudo = ""

	sock = urllib.urlopen("http://hordes.fr/xml/ghost?k=%s;sk=%s"%(key,skey))
	ame = minidom.parse(sock)
	sock.close()
	sock = urllib.urlopen("http://hordes.fr/xml/?k=%s;sk=%s"%(key,skey))
	city = minidom.parse(sock)
	sock.close()

	try: ame
	except NameError:
		self.redirect('/')
	else:
		citizen = ame.getElementsByTagName('citizen')
		headers = ame.getElementsByTagName('headers')
		pseudo = citizen[0].attributes['name'].value
		logging.info('%s se connecte'%pseudo)
		self.response.out.write(citizen)
		self.response.headers.add_header(
		'Set-Cookie',
			'pseudo=%s; expires=Fri, 31-Dec-2020 23:59:59 GMT' \
			  % pseudo)

		session['pseudo'] = pseudo


		me = Player.all().filter('name = ', pseudo.lower()).get()
		if not me:
			me = Player()
			me.name = pseudo.lower()
		try:
			me.avatar = urlfetch.Fetch('%s%s'% \
				(headers[0].attributes['avatarurl'].value,\
				 citizen[0].attributes['avatar'].value)).content
		except:
			me.avatar = ""
		try:
			nowCity = city.getElementsByTagName('city')[0].attributes['city'].value
		except:
			nowCity = u'Ancienne Cité oubliée'
		me.nowCity = nowCity
		me.put()

	#end if
	self.redirect('/')

  def get(self):
	"""bloque la connexion en get si on est pas en Dev"""
	
	pseudo = self.request.get('p')
	if not os.environ['SERVER_SOFTWARE'].startswith('Dev') or pseudo not in ('ozonegrif'):
		self.redirect('/')
		return True
	else:
		session = get_current_session()
		self.response.headers.add_header(
			'Set-Cookie',
			'pseudo=%s; expires=Fri, 31-Dec-2020 23:59:59 GMT'% pseudo)
		session['pseudo'] = pseudo

		self.redirect('/')

class index(webapp.RequestHandler):
  def get(self):
	"""Page d'acceuil."""
	session = get_current_session()
	
	tpl_val = {
			'foo': 'bar',
	}

	path = os.path.join(os.pathname.dirname(__file__), 'index.html')
	self.response.out.write(template.render(path, tpl_val))

application = webapp.WSGIApplication([	# box.py
										('/',		 index),
									], debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

